import os, asyncio
import tkinter as tk
import functools
import contextvars
from tkinter.filedialog import askopenfilename
# from tkinter.filedialog import askopenfilename, askdirectory, asksaveasfilename, askopenfilenames


def tk_window_asksavefile(init_dir=os.getcwd(), suffix='') -> str:
    window = tk.Tk()
    window.wm_attributes('-topmost', 1)
    window.withdraw()
    filename = askopenfilename(initialdir=init_dir, filetypes=[('', suffix)])
    return filename


async def to_thread(func, /, *args, **kwargs):
    loop = asyncio.get_running_loop()
    ctx = contextvars.copy_context()
    func_call = functools.partial(ctx.run, func, *args, **kwargs)
    return await loop.run_in_executor(None, func_call)


asyncio.to_thread = to_thread


async def tk_asksavefile_asy(init_dir=os.getcwd(), suffix='') -> str:
    fname = await asyncio.to_thread(tk_window_asksavefile, init_dir, suffix)
    return fname, fname

